﻿<html>
	<head>
		<title>观察者模式</title>
	</head>
	<body>
		<select>
			<option value="m">男士风格</option>
			<option value="w">女士风格</option>
		</select>
	
		<div id="content">
			<h1>这是内容区域</h1>
		</div>
		<div id="adv">
			<h1> 这里是广告区域</h1>
		</div>
	
	<script type="text/javascript" >
		
		var sel = document.getElementsByTagName("select")[0];
		
		var con = document.getElementById("content");
		var adv = document.getElementById("adv");
		
		sel.observers = {};
		
		// 注册对象
		sel.attch("cont",con);
		sel.attch("ad",adv);
		
		// 注册对象
		sel.attch = function(key,observer){
			this.observers[key] = observer;
		}
		
		// 清除对象
		sel.delObserver = function(key){
			delete this.observers[key];
		}
		
		// 通知对象
		sel.onchange = function(){
			for(var key in this.observers){
				this.observers[key].update(this);
			}
		}
		
		// 对象的更改方法
		con.update = function(obs){
			if(obs.value == 'm'){
				this.style.backgroundColor = "gray";
			}else if(obs.value == 'w'){
				this.style.backgroundColor = "pink";
			}
		}
		
		adv.update = function(obs){
			if(obs.value == 'm'){
				this.innerHTML = "健身";
			}else if(obs.value == 'w'){
				this.innerHTML = "逛街";
			}
		}
		
		
		
	</script>
	
	</body>
</html>




